﻿/*
Copyright © 2011 François Karman

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

See <license.txt> for the complete license of the software.
*/

using System;
using System.Collections.Generic;

namespace Simple.Storage.Api
{
    /// <summary>
    /// Represents the internal state of an <see cref="IndexManager"/>
    /// for a specific persisted instance.
    /// </summary>
    public class IndexManagerNode
    {
        /// <summary>
        /// The key of the instance.
        /// </summary>
        private readonly object key;

        /// <summary>
        /// The index values of the instance for each known index.
        /// </summary>
        private readonly IDictionary<string, object> index;

        /// <summary>
        /// A read-only wrapper for the <see cref="IndexManagerNode.index"/> field.
        /// </summary>
        private readonly IDictionary<string, object> indexRO;

        /// <summary>
        /// Initializes a new instance of the IndexManagerNode class.
        /// </summary>
        /// <param name="key">The key of the instance.</param>
        public IndexManagerNode(object key)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            this.key = key;
            this.index = new Dictionary<string, object>();
            this.indexRO = new ReadOnlyDictionary<string, object>(this.index);
        }

        /// <summary>
        /// Gets the key of the instance.
        /// </summary>
        public object Key
        {
            get { return this.key; }
        }

        /// <summary>
        /// Gets the index values of the instance for each known index.
        /// </summary>
        public IDictionary<string, object> Index
        {
            get { return this.indexRO; }
        }

        /// <summary>
        /// Updates a specified index value.
        /// </summary>
        /// <param name="name">The name of the index.</param>
        /// <param name="value">The new value associated with the index.</param>
        public void UpdateIndex(string name, object value)
        {
            if (this.index.ContainsKey(name))
            {
                this.index[name] = value;
            }
            else
            {
                this.index.Add(name, value);
            }
        }
    }
}
